import datetime

from db_base import StarOrm, CommentOrm


def article_star_comment(result):
    result_ids = [str(i.id) for i in result]
    li = ','.join(result_ids)
    result_dict = result.to_dict()
    temp_sql = lambda x: """
    SELECT
        COUNT( temp.`article_id` ) AS _count 
    FROM
        article AS a
        LEFT JOIN `%s` AS temp ON temp.`article_id` = a.id 
    WHERE
        a.id IN ( %s ) 
    GROUP BY
        a.id
    """ % (x, li)

    star_counts = StarOrm.find_sql(sql=temp_sql('article_star'))
    comment_counts = CommentOrm.find_sql(sql=temp_sql('article_comment'))

    for i in range(len(result_dict)):
        result_dict[i]['star_count'] = star_counts[i]._count
        result_dict[i]['comment_count'] = comment_counts[i]._count

    return result_dict


def ge_echarts(data, orm, Pic, **kwargs):
    dates = [datetime.datetime.now() - datetime.timedelta(days=i) for i in range(7)]
    # 反转
    dates = dates[::-1]

    sums = []

    for i in dates:
        gt_time = i - datetime.timedelta(hours=i.hour, minutes=i.minute, seconds=i.second,
                                         microseconds=i.microsecond)

        lt_time = gt_time + datetime.timedelta(hours=24)

        _seven = orm.orm.find() \
            .where(user_id=data['user_id'],
                   create_time__gt=gt_time,
                   create_time__lt=lt_time, ) \
            .end()
        count = len(_seven)
        sums.append(count)

    return Pic(xData=[i.strftime('%Y-%m-%d') for i in dates], yData=sums, **kwargs)


class EchartsBar:
    """
    echarts柱状图
    """

    def __init__(self, xData: list, yData: list, title="最近七天被点赞数量"):
        self.option = {
            'tooltip': {
                'trigger': 'item'
            },
            'legend': {
                'orient': 'vertical',
                'left': 'left',
            },
            "title": {
                "show": True,
                "text": title
            },
            'xAxis': {
                'type': 'category',
                'data': xData
            },
            'yAxis': {
                'type': 'value'
            },
            'series': [{
                'data': yData,
                'type': 'bar'
            }]
        }


class EchartsLine:
    """
    echarts折线图
    """

    def __init__(self, xData: list, yData: list):
        self.option = {
            'tooltip': {
                'trigger': 'item'
            },
            'legend': {
                'orient': 'vertical',
                'left': 'left',
            },
            "title": {
                "show": True,
                "text": "最近七天发帖频率"
            },
            'xAxis': {
                'type': 'category',
                'data': xData
            },
            'yAxis': {
                'type': 'value'
            },
            'series': [{
                'data': yData,
                'type': 'line'
            }]
        }
